package de.lulusoft.anothertorrent.gui.wizards;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import de.lulusoft.anothertorrent.core.servers.Server;
import de.lulusoft.anothertorrent.core.servers.ServerType;
import de.lulusoft.anothertorrent.gui.AnotherTorrentGui;

public class NewXmlRcpServerWizardPage extends WizardPage {
	
	private Text url = null;
	

	protected NewXmlRcpServerWizardPage(String pageName) {
		super(pageName);
		setTitle(Messages.NewServerWizardPage_0);
		setDescription(Messages.NewServerWizardPage_1);
	}

	@Override
	public IWizardPage getNextPage() {
		return null;
	}

	@Override
	public void createControl(Composite parent) {
		Composite main = new Composite(parent, SWT.NONE);
		main.setLayout(new GridLayout(2, false));
		GridData gd = new GridData();
		gd.horizontalAlignment = SWT.FILL;
		gd.grabExcessHorizontalSpace = true;
		GridData gdInput = new GridData();
		gdInput.horizontalAlignment = SWT.FILL;
		gdInput.grabExcessHorizontalSpace = true;
		
		Label lurl = new Label(main, SWT.NONE);
		lurl.setLayoutData(gd);
		lurl.setText(Messages.NewServerWizardPage_2);
		url = new Text(main, SWT.BORDER | SWT.SINGLE);
		url.setLayoutData(gdInput);
		url.addModifyListener(new ModifyListener() {
		
			@Override
			public void modifyText(ModifyEvent e) {
				setPageComplete(isPageComplete());
			}
		});
		
		// Fill existing server info
		if (((NewServerWizard)getWizard()).edit)
		{
			url.setText(((NewServerWizard)getWizard()).server.getUrl());
		}
		
		setControl(main);
	}
		
	@Override
	public boolean isPageComplete() {
		// TODO: Do real checks here..
		if (url != null && url.getText().trim().length() > 0 // make sure url is set
				)
			return true;
		return false;
	}

	public Server getServer()
	{
		Server server = null;
		try {
			server = new Server(ServerType.XMLRPC,
					((NewServerWizard)getWizard()).selectServerTypeWizardPage.getServerName(),
					url.getText().trim());
		} catch (Exception e) {
			IStatus status = new Status(IStatus.ERROR, AnotherTorrentGui.PLUGIN_ID, "Could not create Server", e);
			AnotherTorrentGui.getDefault().getLog().log(status );
			e.printStackTrace();
		}
		
		return server;
	}

}
